import React, { Component } from "react";
import { connect } from "dva";
import router from "umi/router";
import { routerRedux } from "dva/router";
import { Card, Button, Icon, Divider, message, Tag } from "antd";
import UserSession from "@/UserSession";
import UploadFile from "./uploadFile";
import styles from './index.less';
import PDFView from './pdfView';
import FileView from './fileView';
import RelatedKnowledgeTag from "@/utils/RelatedKnowledgeTag";
import { getRelKnowledgeTagList, postConnectKnowledgeTag } from "@/services/knowledgeLabel";

let timer;
class PreviewFile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			content: '',
			file: null,
			knowledgeTagList: [],
			relatedTagVisible: false,
			pageHeight: 0,
			isPageHeight: false,
		};
	}

	componentDidMount() {
		const { location: { query } } = this.props;
		if (query.fileId) {
			this.info(query.fileId);
		};
		timer = setTimeout(() => {
			this.getPageHeight()
		}, 500)
		window.addEventListener('resize', this.getPageHeight)
	}

	componentWillUnmount() {
		timer && clearTimeout(timer);
		window.removeEventListener('resize', this.getPageHeight)
	}

	getPageHeight = () => {
		console.log(document.getElementById('color_tag_file')?.clientHeight);
		this.setState({ pageHeight: document.getElementById('color_tag_file')?.clientHeight - 76 })
	}

	info = async id => {
		let res = await getRelKnowledgeTagList({ id });
		let knowledgeTagList = [];
		if (res && res.length) {
			res.forEach(item => {
				if (item.tagList && item.tagList.length > 0) {
					item.tagList.forEach(i => {
						knowledgeTagList.push({ color: item.tagColor, id: i.id, name: i.tagValue })
					})
				}
			});
		};
		this.setState({ knowledgeTagList })
	}

	backRouter = () => {
		this.getKnowledgeFileList();
	}

	getKnowledgeFileList = () => {
		const { match: { params: { id }, }, location: { query }, dispatch } = this.props;
		let pathname = "";
		if (UserSession.isSystemKnowledge()) {
			pathname = "/knowledgeDesign/systemKnowledge/" + id + "/file";
		} else {
			pathname = "/knowledgeDesign/myKnowledge/" + id + "/file";
		};
		dispatch(routerRedux.push({ pathname, query: { fileCategoryId: query.fileCategoryId } }));
	}

	updateFile = () => {
		this.uploadFileRef.showModal('UPDATA');
	}

	updateItemFile = (row) => {
		const { location: { params, pathname, query }, dispatch } = this.props;
		dispatch(routerRedux.push({
			pathname,
			query: { fileCategoryId: query.fileCategoryId, fileId: row.id, fileName: row.docName, fileUrl: row.docPath, previewPath: row.previewPath },
		}));
	}

	render() {
		const { match: { params: { id }, }, route, location: { params, query } } = this.props;
		const { knowledgeTagList, relatedTagVisible, pageHeight, isPageHeight } = this.state;
		var index = query.fileName.lastIndexOf(".");
		var type = query.fileName.substr(index + 1);

		return (
			<Card bordered={false}>
				<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '-8px 0 16px' }}>
					<div style={{ fontWeight: 'bold', fontSize: '15px' }}>
						<span>{query.fileName}</span>
						{/* <Icon type="edit" style={{ marginLeft: 6 }} /> */}
					</div>
					<div>
						<Button
							onClick={() => this.openRelatedKnowledgeTagModal()}
							style={{
								backgroundColor: "#FFFFFF",
								color: '#3E5BFF',
								borderColor: '#6478FF',
								// borderRadius: '16px',
								marginRight: 10
							}}
						>
							添加知识标签
						</Button>
						{UserSession.isSystemKnowledge() ? null : (
							<Button type="primary" style={{ marginRight: 10 }} onClick={() => this.updateFile()}>更新版本</Button>
						)}
						<Button onClick={this.backRouter} icon="arrow-left">返回</Button>
					</div>
				</div>
				{knowledgeTagList && knowledgeTagList.length > 0 ? (
					<div style={{ marginBottom: 20, display: 'flex', position: 'relative' }}>
					<div style={{ maxHeight: isPageHeight ? 'unset' : '76px', overflow: 'hidden', flex: 1 }}>
						<span id="color_tag_file" style={{ display: 'flex', flexFlow: 'wrap', gap: '12px', }}>
							<span style={{ lineHeight: '32px', fontWeight: 'bold', fontSize: '14px' }}>关联知识标签：</span>
							{knowledgeTagList.map((item, index) => {
								return (
									<>
										{item.color == '#FFF' || item.color == '#FFFFFF' || item.color == '' ? (
											<Tag
												key={index}
												color={item.color}
												style={{
													padding: '5px 12px',
													fontSize: '14px',
													margin: 0,
													color: item.color + '99',
													background: item.color + '1A',
													// border: '1px solid '+ item.color,
												}}
											>
												<span>{item.name}</span>
												<Icon
													type="close"
													style={{
														color: item.color + '99',
														marginLeft: 8,
													}}
													onClick={() => this.removeRelatedTagData(item)}
												/>
											</Tag>
										) : (
											<Tag
												key={index}
												color={item.color}
												style={{
													padding: '5px 12px',
													fontSize: '14px',
													margin: 0,
													color: item.color + '99',
													background: item.color + '1A',
													// border: '1px solid '+ item.color,
												}}
											>
												<span>{item.name}</span>
												<Icon
													type="close"
													style={{
														color: item.color + '99',
														marginLeft: 8,
													}}
													onClick={() => this.removeRelatedTagData(item)}
												/>
											</Tag>
										)}
									</>
								)
							})}
						</span>
						</div>
						{pageHeight && pageHeight > 0 ? (
							<div style={{ width: '60px' }}>
								<Button
									type="link"
									style={{ position: 'absolute', bottom: '0px', right: '0px', }}
									onClick={() => this.setState({ isPageHeight: !isPageHeight })}
								>
									{isPageHeight ? '收起' : '全部' }
								</Button>
							</div>
						) : null}
					</div>
				) : null}
				<Divider style={{ margin: '0px -24px', width: 'calc(100% + 48px)' }} />
				<div style={{ height: 'calc(100vh - 244px)', overflowY: 'scroll' }} className={styles.view}>
					{type == 'docx' ? (
						<FileView fileType={type} fileUrl={`${window.fileUrl + query.fileUrl}`} fileState={'unset'} />
					) : type == 'txt' ? (
						<iframe class="filename" src={`${window.fileUrl + query.fileUrl}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' />
					) : type == 'pdf' ? (
						// <PDFView file={`${window.fileUrl+query.fileUrl}`} />
						// <FileView fileType={type} fileUrl={`${window.fileUrl+query.fileUrl}`} fileState={'unset'} />
						<iframe class="filename" src={`${window.fileUrl + query.previewPath}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' />
					) : (
						<>
							{/* <FileView fileType={'pdf'} fileUrl={`/cloud/doc/previewDoc?fileUrl=${window.fileUrl+query.fileUrl}`} fileState={'unset'} /> */}
							{/* <PDFView file={`/cloud/doc/previewDoc?fileUrl=${window.fileUrl+query.fileUrl}`} /> */}
							<PDFView file={`${window.fileUrl + query.previewPath}`} fileType={type} />
							{/* <iframe class="filename" src={`${window.fileUrl+query.previewPath}#scrollbars=0&toolbar=0&statusbar=0`} width='100%' height='100%' frameborder='0' /> */}
						</>
					)}
				</div>
				<RelatedKnowledgeTag
					visible={relatedTagVisible}
					onClose={this.closeRelatedTagModal}
					getRelatedList={this.getRelatedTagList}
					onRef={(ref) => (this.RelatedKnowledgeTag = ref)}
				/>
				<UploadFile onRef={ref => this.uploadFileRef = ref} fileId={query.fileId} rootCategoryId={id} updateItemFile={this.updateItemFile} />
			</Card>
		);
	}

	/**
	 * 关联知识标签
	 * @param data
	 * @returns {*}
	 */
	openRelatedKnowledgeTagModal = () => {
		let { knowledgeTagList } = this.state;
		this.RelatedKnowledgeTag.getList(knowledgeTagList);
		this.setState({ relatedTagVisible: true, });
	};

	closeRelatedTagModal = () => {
		this.setState({ relatedTagVisible: false, });
	};

	getRelatedTagList = (data) => {
		this.setState({ knowledgeTagList: data, }, () => {
			this.onRelatedTagSubmit()
		});
	};

	onRelatedTagSubmit = async () => {
		const { location: { query } } = this.props;
		let { knowledgeTagList } = this.state;
		let obj = {
			id: query.fileId,
			knowledgeTagList: knowledgeTagList.map(i => i.id),
		};
		let res = await postConnectKnowledgeTag(obj);
		// console.log(res);
		if (res.code === 0) {
			message.success('操作成功');
		}
	}

	removeRelatedTagData = (tag) => {
		let { knowledgeTagList } = this.state;
		const newData = knowledgeTagList.filter(item => item != tag);
		this.setState({ knowledgeTagList: newData }, () => this.onRelatedTagSubmit());
	};
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(PreviewFile);
